import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  const apiUrl = env.VITE_API_BASE_URL

  console.log('API URL:', apiUrl) // 调试信息

  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      host: 'localhost',
      port: 5173,
      strictPort: true,
      proxy: {
        '/api': {
          target: apiUrl,
          changeOrigin: true,
          secure: false,
          rewrite: (path) => {
            const newPath = path.replace(/^\/api/, '')
            console.log(`代理重写: ${path} -> ${newPath}`) // 调试信息
            return newPath
          },
          configure: (proxy, _options) => {
            proxy.on('error', (err, _req, _res) => {
              console.log('代理错误:', err)
            })
            proxy.on('proxyReq', (proxyReq, req, _res) => {
              console.log('发送请求到目标:', req.method, req.url)
            })
            proxy.on('proxyRes', (proxyRes, req, _res) => {
              console.log('从目标收到响应:', proxyRes.statusCode, req.url)
            })
          }
        }
      }
    }
  }
})